<template>
  <a-modal
    title="选择库存"
    :width="1200"
    :visible="visible"
    :footer="null"
    @cancel="handleCancel">
    
    <div>
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-item label="窗型系列">
                <a-input placeholder="请输入窗型系列" v-model="queryParam.windowSeries"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="窗型编号">
                <a-input placeholder="请输入窗型编号" v-model="queryParam.windowNo"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="库位">
                <a-input placeholder="请输入库位" v-model="queryParam.locationName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        size="small"
        bordered
        rowKey="id"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange">
        
        <template slot="windowInfo" slot-scope="text, record">
          {{ record.windowSeries }} - {{ record.windowNo }} - {{ record.windowColor }}
        </template>
        
        <template slot="availableQuantity" slot-scope="text">
          <span :style="{ color: text > 0 ? '#52c41a' : '#f5222d' }">{{ text }}</span>
        </template>
      </a-table>

      <!-- 底部按钮 -->
      <div style="text-align: right; margin-top: 16px;">
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="confirmSelect" :disabled="selectedRowKeys.length === 0" style="margin-left: 8px;">
          确定选择 ({{ selectedRowKeys.length }})
        </a-button>
      </div>
    </div>

  </a-modal>
</template>

<script>
  import { getAction } from '@/api/manage'

  export default {
    name: 'InventorySelectModal',
    data () {
      return {
        visible: false,
        loading: false,
        dataSource: [],
        selectedRowKeys: [],
        selectedInventoryList: [],
        queryParam: {
          windowSeries: '',
          windowNo: '',
          locationName: ''
        },
        searchParams: {
          orderId: '',
          warehouseId: ''
        },
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        columns: [
          {
            title: '窗型信息',
            dataIndex: 'windowInfo',
            width: 200,
            scopedSlots: { customRender: 'windowInfo' }
          },
          {
            title: '库位',
            dataIndex: 'locationName',
            width: 120
          },
          {
            title: '批次号',
            dataIndex: 'batchNo',
            width: 120
          },
          {
            title: '可用数量',
            dataIndex: 'availableQuantity',
            width: 100,
            align: 'center',
            scopedSlots: { customRender: 'availableQuantity' }
          },
          {
            title: '单价',
            dataIndex: 'unitPrice',
            width: 100,
            align: 'right',
            customRender: (text) => {
              return text ? '¥' + parseFloat(text).toFixed(2) : '-';
            }
          },
          {
            title: '生产日期',
            dataIndex: 'productionDate',
            width: 120
          },
          {
            title: '质量状态',
            dataIndex: 'qualityStatus',
            width: 100,
            align: 'center',
            customRender: (text) => {
              const statusMap = {
                1: '合格',
                2: '不合格',
                3: '待检'
              };
              return statusMap[text] || '未知';
            }
          }
        ]
      }
    },
    methods: {
      show(params) {
        this.visible = true;
        this.selectedRowKeys = [];
        this.selectedInventoryList = [];
        this.searchParams = params || {};
        this.loadData();
      },
      loadData() {
        this.loading = true;
        const params = {
          pageNo: this.ipagination.current,
          pageSize: this.ipagination.pageSize,
          ...this.queryParam,
          ...this.searchParams,
          // 只查询可用库存（数量大于0且质量状态为合格）
          availableOnly: true
        };
        
        // 这里调用库存查询接口，需要根据实际的库存模块API调整
        getAction('/wms/inventory/availableList', params).then(res => {
          if (res.success) {
            this.dataSource = res.result.records || [];
            this.ipagination.total = res.result.total || 0;
          } else {
            this.$message.error(res.message || '查询库存失败');
          }
        }).catch(err => {
          console.error('查询库存失败:', err);
          this.$message.error('查询库存失败');
        }).finally(() => {
          this.loading = false;
        });
      },
      searchQuery() {
        this.ipagination.current = 1;
        this.loadData();
      },
      searchReset() {
        this.queryParam = {
          windowSeries: '',
          windowNo: '',
          locationName: ''
        };
        this.ipagination.current = 1;
        this.loadData();
      },
      handleTableChange(pagination) {
        this.ipagination = pagination;
        this.loadData();
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectedInventoryList = selectedRows;
      },
      confirmSelect() {
        if (this.selectedInventoryList.length > 0) {
          // 过滤掉数量为0的库存
          const validInventoryList = this.selectedInventoryList.filter(item => item.availableQuantity > 0);
          if (validInventoryList.length === 0) {
            this.$message.warning('所选库存可用数量为0，请重新选择！');
            return;
          }
          this.$emit('ok', validInventoryList);
          this.handleCancel();
        }
      },
      handleCancel() {
        this.visible = false;
        this.selectedRowKeys = [];
        this.selectedInventoryList = [];
        this.queryParam = {
          windowSeries: '',
          windowNo: '',
          locationName: ''
        };
        this.searchParams = {
          orderId: '',
          warehouseId: ''
        };
      }
    }
  }
</script>
